package com.example.controller;

import com.example.util.RedisLockUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class SpikeController {
    @Autowired
    private RedissonClient redissonClient;
    private final String LOCK_KEY = "spike-lock";
    private int kucun = 5;

    @GetMapping("spike")
    public String spike() {
        String uid = Thread.currentThread().getName();
        RLock fairLock = redissonClient.getFairLock(LOCK_KEY);
        try {
            if (kucun > 0) {

                fairLock.lock();
                if (kucun > 0) {
                    TimeUnit.SECONDS.sleep(4);
                    kucun--;
                    System.out.println(uid + "已参与秒杀");
                    System.out.println("还剩余" + kucun + "商品");
                    if (fairLock.isLocked() && fairLock.isHeldByCurrentThread()) {
                        fairLock.unlock();
                    }
                    return "亲爱的" + uid + "顾客，你已参与秒杀，请稍后";
                } else {
                    System.out.println("库存已空");
                    return "亲爱的" + uid + "顾客，商品已被秒杀完";
                }
            } else {
                System.out.println("库存已空");
                return "亲爱的" + uid + "顾客，商品已被秒杀完";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fairLock.unlock();
        }
        return null;
    }

}
